package com.my.blogapi.handler;

import com.alibaba.fastjson.JSON;
import com.my.blogapi.dao.pojo.SysUser;
import com.my.blogapi.service.LoginService;
import com.my.blogapi.service.SysUserService;
import com.my.blogapi.utils.JWTUtils;
import com.my.blogapi.utils.UserThreadLoacl;
import com.my.blogapi.vo.ErrorCode;
import com.my.blogapi.vo.param.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private LoginService loginService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 对用户登录登陆状态进行检测 在controller执行之前
         * 判断逻辑
         * 1. 请求访问的是不是一个handler
         * 2.判断token是否为空
         * 3.登录验证token
         * 4.认证成功 放行
         */
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader("Authorization");
        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}", requestURI);
        log.info("request method:{}", request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");

        if (StringUtils.isBlank(token)) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().println(JSON.toJSONString(Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg())));
            return false;
        }
        //对token进行验证
        SysUser sysUser = loginService.checkToken(token);
        if (sysUser == null) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().println(JSON.toJSONString(Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg())));
            return false;
        }
        UserThreadLoacl.put(sysUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //如果不删，会有内存泄露的风险
        UserThreadLoacl.remove();
    }
}
